package com.xx.mp.mapper;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.Map;

public class SelectIgnoreLogicDeleteByMap extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        String sqlBase= "<script>SELECT %s FROM %s %s\n</script>";
        String sqlScript = this.sqlWhereByMap(tableInfo);
        String sql = String.format(sqlBase, this.sqlSelectColumns(tableInfo, false), tableInfo.getTableName(), sqlScript);
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, Map.class);
        return this.addSelectMappedStatementForTable(mapperClass, "selectIgnoreLogicDeleteByMap", sqlSource, tableInfo);
    }

    /**
     * 拼接where条件根据map参数
     *
     * @param table 表
     * @return sql
     */
    protected String sqlWhereByMap(TableInfo table) {
        String sqlScript;
        sqlScript = SqlScriptUtils.convertChoose("v == null", " ${k} IS NULL ", " ${k} = #{v} ");
        sqlScript = SqlScriptUtils.convertForeach(sqlScript, "cm", "k", "v", "AND");
        sqlScript = SqlScriptUtils.convertWhere(sqlScript);
        sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null and !%s", "cm", "cm.isEmpty"), true);
        return sqlScript;
    }
}
